<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改活动信息"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入活动标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="活动简介" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入活动简介"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="活动地点" prop="location">
        <el-input
          v-model="formData.location"
          placeholder="请输入活动地点"
          maxlength="200"
        />
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="人数限制" prop="maxParticipants">
        <el-input-number
          v-model="formData.maxParticipants"
          :min="0"
          :max="10000"
          placeholder="0表示不限制"
          style="width: 100%"
        />
        <span style="margin-left: 10px; color: #909399; font-size: 12px">
          0表示不限制人数
        </span>
      </el-form-item>

      <el-form-item label="活动图片">
        <el-upload
          v-model:file-list="fileList"
          :action="uploadUrl"
          :headers="uploadHeaders"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :limit="6"
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <div class="tip">最多上传6张图片，每张不超过5MB</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          保存修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { reqGetActivityDetail, reqUpdateActivity } from '@/api/activity'
import type { ActivityItem } from '@/api/activity/type'
import { GET_TOKEN } from '@/utils/token'
import dayjs from 'dayjs'

const props = defineProps<{
  modelValue: boolean
  activityId: number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)

// 上传接口地址和请求头
const uploadUrl = '/api/activity/upload/image'
const uploadHeaders = computed(() => ({
  token: GET_TOKEN() || ''
}))

const formData = ref({
  title: '',
  description: '',
  location: '',
  startTime: '',
  endTime: '',
  maxParticipants: 0,
  images: [] as string[]
})

const fileList = ref<UploadUserFile[]>([])

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动简介', trigger: 'blur' },
    { min: 10, max: 500, message: '简介长度在10-500个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.startTime) {
          if (dayjs(value).isBefore(dayjs(formData.value.startTime))) {
            callback(new Error('结束时间不能早于开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 获取活动详情
const getActivityDetail = async () => {
  if (!props.activityId || loading.value) return
  loading.value = true

  try {
    const result: any = await reqGetActivityDetail(props.activityId)
    if (result.code === 200) {
      const activity: ActivityItem = result.data

      // 设置表单数据
      formData.value = {
        title: activity.title,
        description: activity.description,
        location: activity.location,
        startTime: activity.startTime,
        endTime: activity.endTime,
        maxParticipants: activity.maxParticipants,
        images: [...(activity.images || [])] // 复制数组
      }

      // 设置图片列表（用于显示）
      fileList.value = (activity.images || []).map((url, index) => ({
        name: `image-${index}.jpg`,
        url: url,
        uid: Date.now() + index,
        status: 'success'
      }))

      console.log('加载的活动详情:', formData.value)
      console.log('图片列表:', fileList.value)
    } else {
      ElMessage.error(result.message || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 上传成功回调
const handleUploadSuccess = (response: any, uploadFile: any) => {
  console.log('上传成功响应:', response)
  if (response.code === 200) {
    // 将新上传的图片URL添加到images数组
    formData.value.images.push(response.data.url)
    ElMessage.success('图片上传成功')
  } else {
    // 上传失败，从文件列表中移除
    const index = fileList.value.findIndex(file => file.uid === uploadFile.uid)
    if (index > -1) {
      fileList.value.splice(index, 1)
    }
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 删除图片
const handleRemove = (uploadFile: any) => {
  // 从文件列表中获取图片URL
  const url = uploadFile.response?.data?.url || uploadFile.url

  // 从images数组中移除
  const index = formData.value.images.indexOf(url)
  if (index > -1) {
    formData.value.images.splice(index, 1)
  }

  console.log('删除图片后的images:', formData.value.images)
}

// 上传前验证
const beforeUpload = (file: File) => {
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }

  // 验证文件大小
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }

  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证是否有图片
      if (formData.value.images.length === 0) {
        ElMessage.warning('请至少上传一张活动图片')
        return
      }

      submitLoading.value = true

      try {
        // 确保日期格式正确（将 ISO 格式转换为 yyyy-MM-dd HH:mm:ss）
        const submitData = {
          ...formData.value,
          startTime: formData.value.startTime.includes('T') 
            ? formData.value.startTime.replace('T', ' ').substring(0, 19)
            : formData.value.startTime,
          endTime: formData.value.endTime.includes('T')
            ? formData.value.endTime.replace('T', ' ').substring(0, 19)
            : formData.value.endTime
        }
        
        console.log('提交的数据:', submitData)

        const result: any = await reqUpdateActivity(props.activityId, submitData)

        if (result.code === 200) {
          ElMessage.success('修改成功')
          emit('success')
          handleClose()
        } else {
          ElMessage.error(result.message || '修改失败')
        }
      } catch (error: any) {
        console.error('修改活动失败:', error)
        ElMessage.error(error.message || '修改活动失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  fileList.value = []
  formData.value.images = []
  emit('update:modelValue', false)
}

// 监听对话框打开
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.activityId) {
    getActivityDetail()
  }
})
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    width: 100px;
    height: 100px;
  }
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>
